//
//  ongoingOrdersViewController.m
//  QXDLLOrdersModule
//
//  Created by DL on 17/1/4.
//  Copyright © 2017年 DLL. All rights reserved.
//

#import "ongoingOrdersViewController.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "orderDetailsViewController.h"
#import "endTheTripViewController.h"
#import "carEndTheTripViewController.h"
#import "progressOrderDetailsViewController.h"
#import "QXSlidingButton.h"
#import "DLLApiManager.h"
#import "NavigationMap.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import "MapViewRoutePlan.h"
#import "HeaderMacro.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "LocationManager.h"
#import "UserLocationModel.h"
#import "NaviVC.h"
#import "progressOrderDetailsViewController.h"
#import "paymentOrderDetailsViewController.h"
#import <QXSocketManager/QXSocketManager.h>
#import "MapGeometryCalculationManager.h"
#import "DetailsOfChargesVC.h"
#import "HeaderMacro.h"
#import "IflyMSCManager.h"
#import "iflyMSC/iflyMSC.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "ConfigureKeyHeader.h"
#import <QXDataManager/QXDataManager.h>
#import <QXYueYueModels/QXYYUserDriverModel.h>
#import <MAMapKit/MATraceLocation.h>
#import "TrajectoryCorrectionManager.h"
#import "NotificationNameManager.h"
#import <MAMapKit/MATraceManager.h>
#import "IflyMSCManager.h"
#import "NotificationNameManager.h"
#import "CarImageManager.h"
#import "SendLocationManager.h"
#import "SendLocationModel.h"
#import "NaviDriveManager.h"
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>
#import "OrderClosingManager.h"


#import <MapboxDirections/MapboxDirections.h>
#import <MapboxNavigation/MapboxNavigation.h>
#import <MapboxDirections/MapboxDirections.swift-umbrella.h>
#import <MapboxNavigation/MapboxNavigation-Swift.h>
#import <MapboxCoreNavigation/MapboxCoreNavigation.h>
#import <MapboxCoreNavigation/MapboxCoreNavigation-umbrella.h>

#import "MapManager.h"



#import "CustomMGLAnnotationView.h"
#import "CustomMGLPointAnnotation.h"


@interface ongoingOrdersViewController ()<AMapNaviDriveViewDelegate , AMapNaviDriveManagerDelegate, AMapNaviDriveDataRepresentable , MGLMapViewDelegate>

/// 导航管理器
@property(nonatomic , strong) AMapNaviDriveManager *driveManager;

/// 导航地图
@property(nonatomic , strong) AMapNaviDriveView *driveView;

/// 导航栏左侧按钮
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftBarButtonItem;
/// 点
@property (weak, nonatomic) IBOutlet UIImageView *pointImageView;
/// 起点位置
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
/// 状态
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
/// 手机尾号
@property (weak, nonatomic) IBOutlet UILabel *phoneTailNumberLabel;
/// 上车标签
@property (weak, nonatomic) IBOutlet UILabel *getOnLabel;

/// 导航
@property (weak, nonatomic) IBOutlet UIButton *navigationButton;
/// 拨打电话
@property (weak, nonatomic) IBOutlet UIButton *callPhoneButton;
/// 展示距离时间
@property (weak, nonatomic) IBOutlet UIView *displayView;
/// 距离
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
/// 时间
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
/// 底部滑动按钮
@property (weak, nonatomic) IBOutlet QXSlidingButton *bottomView;
@property (weak, nonatomic) IBOutlet UIImageView *bottomImageView;

/// 定位
@property (weak, nonatomic) IBOutlet UIButton *positioningButton;
/// 路况
@property (weak, nonatomic) IBOutlet UIButton *roadConditionsButton;
/// 价格
@property (weak, nonatomic) IBOutlet UIButton *fareButton;
/// 状态按钮距左侧约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changeStatusLayoutConstraint;



@property (weak, nonatomic) IBOutlet UIView *mapBackView;

/**
 展示时间公里数的背景视图高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *displayViewHeight;


/**
 头的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerHeight;

/**
 尾部的高度
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;


/**
 订单行程状态
 */
@property(nonatomic , assign) OrderStatusEnumCode orderState;


/**
 加载时间和路径的loading背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *calculationTimeAndDistanceBackView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorView;



/**
 滑动按钮距离屏幕左侧的距离,到达上车地点以前距离为0,到达上车地点后在100
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *slidingButtonMargin_ToLeft;


/**
 是否规划路径成功
 */
@property(nonatomic , assign) BOOL isOnCalculateRouteSuccess;


/**
 导航loading 背景视图
 */
@property (weak, nonatomic) IBOutlet UIView *navigationActivityBackView;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *navigationActivityView;


/**
 剩余时间距离的定时器
 */
@property(nonatomic , strong) NSTimer *timer_TimeDistance;

/**
 时间累计
 */
@property(nonatomic , assign) NSInteger timeAccumulation;

@property(nonatomic , strong) NSTimer *timer;

@property(nonatomic , assign) double newLat; // 最新的精度
@property(nonatomic , assign) double newLng; // 最新的纬度
@property(nonatomic , assign) NSInteger newAngle; // 最新的角度
@property(nonatomic , assign) double newDistance; // 最新的距离 单位: 公里

//@property (weak, nonatomic) IBOutlet UILabel *hasDriverDistance;

@property (weak, nonatomic) UILabel *hasDriverDistance;



/**
 轨迹纠偏获取的经纬度的集合
 */
@property(nonatomic , strong) NSMutableArray<MATraceLocation *> *tracePointArray;

/// 轨迹纠偏管理器
//@property(nonatomic , strong) MATraceManager *traceManager;
@property(nonatomic , strong) MATraceLocation *traceLocation;

@property(nonatomic , strong) TrajectoryCorrectionManager *trajectoryCorrectionManager;

@property(nonatomic , assign) BOOL isNaviOver; // 是否导航结束

@property(nonatomic , strong) MAPointAnnotation *annotation_Dest;
//@property(nonatomic , strong) MAPointAnnotation *annotation_Dest;

// 默认为NO
@property(nonatomic , assign) BOOL isReceivedMsgOfOrderCanceled;

@property(nonatomic , strong) MAMapView *mapView;




/// 每次启动都要获取一次服务端的最新的总距离,单位: 公里
@property(nonatomic , assign) double theLastedTotalDidstanceFromService;

/// 每次启动都要获取一次服务端的最近点位置坐标
@property(nonatomic , assign) CLLocationCoordinate2D theLastedCLLocationFromService;

/// 获取最近的刚启动高德地图的位置信息
@property(nonatomic , assign) CLLocationCoordinate2D theLastedCLLocationFromGK;

/// 如果app死掉,丢失的两位置之间的直线距离 , 单位公里
@property(nonatomic , assign) double theLostLineDistance;

/// 是否获取到了刚启动高德地图发送的第一个位置点,默认为NO
@property(nonatomic , assign) BOOL isGetFirstLocation;

/// 是否从服务器获取到了最新的位置信息,默认为NO
@property(nonatomic , assign) BOOL isGetTheLastedLocationInfoFromeService;

/// 是否获取到了丢失位置之间的直线距离,默认为NO
@property(nonatomic , assign) BOOL isGetTheLostLineDistance;

@property(nonatomic , assign) double tempNumber;

@property(nonatomic , strong) UILabel *sendMsg;

/// 行驶距离单位: 公里
@property(nonatomic , assign) double drivingDistance;

/// 进程
@property(nonatomic , strong) NSOperation *operation;

/// 是否正在轨迹纠偏
@property(nonatomic , assign) BOOL isTraceCorrect;

/// 之前的距离单位: 公里,本地缓存的距离
@property(nonatomic , assign) double distanceBefore;

/// app 挂掉获取最新的两点之间的距离 单位: 公里
@property(nonatomic , assign) double tempDistanceOfTwoPoint;

/// 如果在这个页面那么不在播报语音,在详细导航页面开始播报语音
@property(nonatomic , assign) BOOL isPlayingNaviInfo;


/// mapbox 属性
/// mapbox 地图需要用到的参数
@property (nonatomic , strong) MGLMapView *mapboxMapView;
/// 当前显示在地图上的路线
@property (nonatomic , strong) MGLPolyline *currentRouteLine;
/// 导航起始点大头针
@property (nonatomic , strong) CustomMGLPointAnnotation *orginPin;
/// 导航终点大头针
@property (nonatomic , strong) CustomMGLPointAnnotation *destPin;
/// 导航信息控制器
@property (nonatomic , strong) MBRouteController *routeVC;
/// 当前路线
@property (nonatomic , strong) MBRoute *currentRoute;




@end

@implementation ongoingOrdersViewController
- (NSMutableArray *)tracePointArray {

    if (!_tracePointArray) {
        self.tracePointArray = [NSMutableArray array];
    }
    return _tracePointArray;
}



+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"ongoingOrdersViewController"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self initTrajectoryCorrectionManagerWithOrderId:self.ordersDetailsModel.uuid]; // 加载行驶里程的计算

    
    // 配置默认属性
    [self configureDefaultAttributes];
    
    
    if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        // 加载高德地图导航模块功能
        [self initNaviManager];
    }else {
        
        // 加载 mapbox 地图模块
        [self initMapboxMapView];
    }

    
    /// 注册用户定位信息发生改变的通知
    [self registerDriverHasChangedLocation];

    /// 获取长连接返回的报文
    [self regisetrUPLOAD_LOCATION_RESPONSENotification];
    
    
    
    [self registerRealFareNotification];
    
    [self getWaitingFareWithSendLocationManager:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[OrderClosingManager shareManager] openNotificationWithOrderUuid:self.ordersDetailsModel.uuid receivedNotification:^(NSNotification *aNotification) {
        
    }];
}


#pragma mark - 注册获取实时费用的通知
- (void)registerRealFareNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWaitingFareWithSendLocationManager:) name:NotificationName_GetRealFare object:nil];
}

- (void)getWaitingFareWithSendLocationManager:(NSNotification *)aNotification {
    
    if (self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) { // 如果订单处于等待乘客状态,刷新超时等待费用
        
        [self getWaitingFare];
    }
    
    // 实时跟新价格
    if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
        
        [self getDriverRealTimePrice]; // 刚进来的时候获取一下最新的价格,针对app挂掉
    }
}

#pragma mark - 注销通知
- (void)cancelNotification {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_GetRealFare object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_UserLocationChanged object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName_UPLOAD_LOCATION_RESPONSE object:nil];

}





/**
 初始化轨迹纠偏的管理类

 @param orderId 订单ID
 */
- (void)initTrajectoryCorrectionManagerWithOrderId:(NSString *)orderId {
    
    self.trajectoryCorrectionManager = [TrajectoryCorrectionManager initWithOrderID:orderId];
    
    self.orderState = self.ordersDetailsModel.subStatus;
}


#pragma mark - 刷新剩余距离和剩余时间UI
- (void)refreshDistanceAndTimeWithMapPath:(AMapNaviRoute *)aMapPathRoute {
    
    if (aMapPathRoute == nil) {
        
        return;
    }
    
    CGFloat distance = aMapPathRoute.routeLength / 1000.00; // 公里
    if (distance < 1) {
        
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2f米" , distance * 1000];
    }else {
        
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2f公里" , distance];
    }
    
    
    CGFloat time = aMapPathRoute.routeTime / 60.0; // 转化分钟
    self.timeLabel.text = [NSString stringWithFormat:@"%.f分钟" , time];
    [self.activityIndicatorView stopAnimating];
    self.calculationTimeAndDistanceBackView.hidden = YES;
    
}

#pragma mark - 加载 mapbox 导航模块
/// 初始化 mapbox 地图
- (void)initMapboxMapView {
    
    self.mapboxMapView = [[MGLMapView alloc] initWithFrame:self.mapBackView.bounds];
    self.mapboxMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapboxMapView.delegate = self;
    [self.mapBackView addSubview:self.mapboxMapView];
    [self.mapboxMapView setUserTrackingMode:(MGLUserTrackingModeFollow)];
    
    [self registerNotificatoinDriverDidChanged];
}

/**
 重新绘制地图路线
 */
- (void)reDrawMapBoxRoute {
    
    self.navigationActivityBackView.hidden = NO;
    [self.navigationActivityView startAnimating];
    
    if (self.orginPin != nil) {
        
        [self.mapboxMapView removeAnnotation:self.orginPin];
        
    }
    
    if (self.destPin != nil) {
        
        [self.mapboxMapView removeAnnotation:self.destPin];
    }
    
    
    if (self.orginPin == nil) {
        
        self.orginPin = [[CustomMGLPointAnnotation alloc] init];
    }
    
    if ( self.destPin == nil) {
        
        self.destPin = [[CustomMGLPointAnnotation alloc] init];
    }

    
    

    
    if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) { // 去接乘客
        
        
        self.orginPin.identifier = @"";
        self.orginPin.title = @"";
        
        self.destPin.identifier = @"起点";
        self.destPin.title = @"起点";
        
        self.orginPin.coordinate = CLLocationCoordinate2DMake(self.mapboxMapView.userLocation.location.coordinate.latitude, self.mapboxMapView.userLocation.location.coordinate.longitude);
        
        self.destPin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.originLat, self.ordersDetailsModel.originLng);
        
        [self.mapboxMapView addAnnotations:@[self.orginPin , self.destPin]];
        
        MBWaypoint *orginWaypoint = [[MBWaypoint alloc] initWithCoordinate:self.orginPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"起点"];
        MBWaypoint *destWaypoint = [[MBWaypoint alloc] initWithCoordinate:self.destPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"终点"];
        [self drawRouteLine:@[orginWaypoint , destWaypoint]];
        
    }else if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 接到乘客,前往目的地
        
        if ([self.ordersDetailsModel.typeTime integerValue] == OrderPushTypeDaiyRental || [self.ordersDetailsModel.typeTime integerValue] == OrderPushTypeHalfDayRent) { // 日租/半日租

            
            self.mapboxMapView.userTrackingMode = MGLUserTrackingModeFollowWithHeading;
            [self.navigationActivityView stopAnimating];
            self.navigationActivityBackView.hidden = YES;
            
            [self.mapboxMapView removeAnnotations:@[self.orginPin , self.destPin]];
            [self.mapboxMapView removeOverlay:self.currentRouteLine];
            self.currentRoute = nil;
            self.routeVC = nil;

            
        }else {
            
            
            self.orginPin.identifier = @"";
            self.orginPin.title = @"";
            
            self.destPin.identifier = @"终点";
            self.destPin.title = @"终点";
            
            self.orginPin.coordinate = CLLocationCoordinate2DMake(self.mapboxMapView.userLocation.location.coordinate.latitude, self.mapboxMapView.userLocation.location.coordinate.longitude);
            
            self.destPin.coordinate = CLLocationCoordinate2DMake(self.ordersDetailsModel.destLat, self.ordersDetailsModel.destLng);
            
            [self.mapboxMapView addAnnotations:@[self.orginPin , self.destPin]];
            
            MBWaypoint *orginWaypoint = [[MBWaypoint alloc] initWithCoordinate:self.orginPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"起点"];
            MBWaypoint *destWaypoint = [[MBWaypoint alloc] initWithCoordinate:self.destPin.coordinate coordinateAccuracy:(kCLLocationAccuracyBest) name:@"终点"];
            [self drawRouteLine:@[orginWaypoint , destWaypoint]];

        }
        
    }else if (self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
        
        
    }
}


- (void)drawRouteLine:(NSArray<MBWaypoint *> *)waypoints {
    
    if (waypoints.count < 2) {
        
        return;
    }
    
    MBRouteOptions *options = [[MBRouteOptions alloc] initWithWaypoints:waypoints profileIdentifier:MBDirectionsProfileIdentifierAutomobileAvoidingTraffic];
    options.includesSteps = YES;
    
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [[MBDirections sharedDirections] calculateDirectionsWithOptions:options completionHandler:^(NSArray<MBWaypoint *> * _Nullable waypoints, NSArray<MBRoute *> * _Nullable routes, NSError * _Nullable error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (error == nil) {
            
            if (routes != nil) {
                
                MBRoute *route = routes.firstObject;
                
                if (route != nil) {
                    
                    
                    if (route.coordinateCount > 0) {
                        
                        if (strongSelf.currentRouteLine != nil) {
                            
                            [strongSelf.mapboxMapView removeOverlay:strongSelf.currentRouteLine];
                            [strongSelf.mapboxMapView removeAnnotations:@[strongSelf.orginPin , strongSelf.destPin]];
                        }
                        
                        CLLocationCoordinate2D *routeCoordinates = malloc(route.coordinateCount * sizeof(CLLocationCoordinate2D));
                        [route getCoordinates:routeCoordinates];
                        MGLPolyline *routeLine = [MGLPolyline polylineWithCoordinates:routeCoordinates count:route.coordinateCount];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            [strongSelf.activityIndicatorView stopAnimating];
                            strongSelf.calculationTimeAndDistanceBackView.hidden = YES;
                            
                            [strongSelf.navigationActivityView stopAnimating];
                            strongSelf.navigationActivityBackView.hidden = YES;
                            
                            if (route.distance < 1000) {
                                
                                strongSelf.distanceLabel.text = [NSString stringWithFormat:@"%.1f米" , route.distance];
                            } else {
                                
                                strongSelf.distanceLabel.text = [NSString stringWithFormat:@"%.1f公里" , route.distance / 1000];
                            }
                            
                            strongSelf.timeLabel.text = [NSString stringWithFormat:@"%.1f分钟" , route.expectedTravelTime / 60.0];
                        });
                        
                        strongSelf.currentRouteLine = routeLine;
                        // Add the polyline to the map and fit the viewport to the polyline.
                        [strongSelf.mapboxMapView addAnnotation:routeLine];
                        [strongSelf.mapboxMapView setVisibleCoordinates:routeCoordinates count:route.coordinateCount edgePadding:UIEdgeInsetsMake(30, 30, 100, 30) animated:YES];
                        
                        strongSelf.routeVC = [[MBRouteController alloc] initWithRoute:route directions:[MBDirections sharedDirections]];
                        [strongSelf.routeVC resume];
                    
                    
                        
                        strongSelf.currentRoute = route;
                        // Make sure to free this array to avoid leaking memory.
                        free(routeCoordinates);
                    }
                }

            }
        }else {
            
            
        }
    }];
    
    [task resume];
}

#pragma mark - 注册通知观察 MGLMapbox 的导航信息
- (void)registerNotificatoinDriverDidChanged {
//    RouteControllerProgressDidChange
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverDidChnanged:) name:MBRouteControllerNotificationProgressDidChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverDidChnanged:) name:MBRouteControllerWillReroute object:nil];
}
- (void)driverDidChnanged:(NSNotification *)aNotification {
    
    if (aNotification.userInfo != nil && [aNotification.name isEqualToString:MBRouteControllerNotificationProgressDidChange]) {
        
        if (aNotification.userInfo[MBRouteControllerProgressDidChangeNotificationProgressKey] != nil) {
            
            
            MBRouteProgress *progress = aNotification.userInfo[MBRouteControllerProgressDidChangeNotificationProgressKey];
            if (progress.distanceRemaining < 1000) {
                
                self.distanceLabel.text = [NSString stringWithFormat:@"%.1f米" , progress.distanceRemaining];
            } else {
                
                self.distanceLabel.text = [NSString stringWithFormat:@"%.1f公里" , progress.distanceRemaining / 1000.0];
            }
            
            self.timeLabel.text = [NSString stringWithFormat:@"%.1f分钟" , progress.durationRemaining / 60.0];
        }
    }
    
    if (aNotification.userInfo != nil && [aNotification.name isEqualToString:MBRouteControllerWillReroute]) { // 如果偏航了从新规划路线
        
        [self reDrawMapBoxRoute];
    }
}

#pragma mark - MGLMapViewDelegate
- (void)mapViewWillStartLoadingMap:(MGLMapView *)mapView {
    
    
}

- (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
    
    NSLog(@"地图%.9f -- %.9f" , mapView.userLocation.coordinate.latitude , mapView.userLocation.coordinate.longitude);
    NSLog(@"%.9f -- %.9f" , [LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude , [LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude);
    [self reDrawMapBoxRoute];
}

- (void)mapViewDidFailLoadingMap:(MGLMapView *)mapView withError:(NSError *)error {
    
    
}

- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation {
    
    
    
    double lat = userLocation.location.coordinate.latitude;
    double lng = userLocation.location.coordinate.longitude;
    double angle = userLocation.location.course;
    
    
    
    if (lat == 0 || lng == 0) { // 如果没有获取到正确的位置信息不执行
        
        return;
    }
    
    self.newLat = lat;
    self.newLng = lng;
    self.newAngle = angle;
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
    [self.trajectoryCorrectionManager add:coordinate];
    
    double twoPointDistance = [self.trajectoryCorrectionManager getThelastedDistance] /  1000.0;
    double totalDistance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;
    
    if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers || self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
        
        
        [[SendLocationManager shareManager] configureModelInfoOfHasOrderWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:self.orderState isSendImmediately:NO];
    }
    
    
    if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 如果接到乘客,开始添加位置点
        
        [[SendLocationManager shareManager] configureModelInfoOfOngoingOrderAndSendLocationInfoWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:self.orderState isSendImmediately:NO];
    }
}

- (void)mapViewWillStartLocatingUser:(MGLMapView *)mapView {
    

}

- (void)mapViewDidStopLocatingUser:(MGLMapView *)mapView {
    

}

- (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
    
    static NSString *DriverIdentifier = @"Driver";
    static NSString *PinIdentifier = @"Annotation";
    if ([annotation isKindOfClass:[MGLUserLocation class]]) {
        
        MGLUserLocationAnnotationView *userAnnotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:DriverIdentifier];
        
        if (userAnnotationView == nil) {
            
            userAnnotationView = [[MGLUserLocationAnnotationView alloc] initWithReuseIdentifier:DriverIdentifier];
            //            userAnnotationView.userLocation.locatio
            UIImageView *userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            [userAnnotationView addSubview:userImageView];
            userImageView.image = [CarImageManager getCarImage];
            userImageView.layer.cornerRadius = userImageView.frame.size.height / 2.0;
            userImageView.layer.masksToBounds = YES;
            userImageView.backgroundColor = [UIColor clearColor];
            userImageView.contentMode = UIViewContentModeCenter;
            
            
        }
        
        
        return userAnnotationView;
    }
    
    
    
    if ([annotation isKindOfClass:[CustomMGLPointAnnotation class]]) {
        
        CustomMGLAnnotationView *annotationView = (CustomMGLAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:PinIdentifier];
        
        if (annotationView == nil) {
            
            annotationView = [[CustomMGLAnnotationView alloc] initWithReuseIdentifier:PinIdentifier];
            annotationView.frame = CGRectMake(0, 0, 30, 30);
        }
        
        CustomMGLPointAnnotation *customPointAnnotation = (CustomMGLPointAnnotation *)annotation;
        
        if (customPointAnnotation != nil) {
            
            annotationView.backgroundColor = [UIColor clearColor];
            if ([customPointAnnotation.identifier isEqualToString:@"起点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                
            }else if ([customPointAnnotation.identifier isEqualToString:@"终点"]) {
                
                annotationView.imageView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
            }
        }
        
        return annotationView;
    }
    
    return nil;
}


#pragma mark - 加载高德地图导航模块
- (void)initNaviManager {
    
//    if (self.driveManager == nil) {
//        
//        self.driveManager = [[AMapNaviDriveManager alloc] init];
//        [self.driveManager setDelegate:self];
//        [self.driveManager setEmulatorNaviSpeed:120];
//        [self initNaviDriveView];
//        
//        [self.driveManager setAllowsBackgroundLocationUpdates:YES];
//        [self.driveManager setPausesLocationUpdatesAutomatically:NO];
//    }
    
    [[NaviDriveManager shareManager] setDelegate:self];
    [[NaviDriveManager shareManager] setEmulatorNaviSpeed:120];
    [[NaviDriveManager shareManager] setAllowsBackgroundLocationUpdates:YES];
    [[NaviDriveManager shareManager] setPausesLocationUpdatesAutomatically:NO];
    
    [self initNaviDriveView];
}


- (void)initNaviDriveView {
    
    if (self.driveView == nil)
    {
        self.driveView = [[AMapNaviDriveView alloc] initWithFrame:self.mapBackView.bounds];
        self.driveView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.driveView setDelegate:self];
        [self.driveView setShowUIElements:NO];
        [self.driveView setCarImage:[CarImageManager getCarImage]];
        if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers || self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
            
            [self.driveView setEndPointImage:[QXDriverConfiguration imageWithName:@"public_pic_qidian"]];
        }else {
            
            [self.driveView setEndPointImage:[QXDriverConfiguration imageWithName:@"public_pic_zhongdian"]];
        }
        
        [self.mapBackView addSubview:self.driveView];

        
        [self.driveView setMapZoomLevel:18];
//        [self.driveManager addDataRepresentative:self.driveView];
        [[NaviDriveManager shareManager] addDataRepresentative:self.driveView];
    }
    
    if (self.driveManager != nil) {
        
//        [self initRoute]; // 导航路线
    }
    
    [self initRoute]; // 导航路线
}


#pragma mark - 导航模块加载完成后,开始导航线路规划
- (void)initRoute {
    
    if (![LocationManager shareManager].userLocationModel) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"地图定位失败" onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    }else {
        
        [self reDrawMapRoute];
    }
}


/**
 重新绘制地图路线
 */
- (void)reDrawMapRoute {
    
    self.navigationActivityBackView.hidden = NO;
    [self.navigationActivityView startAnimating];
    
    if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) { // 去接乘客
        
        AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude];
        AMapGeoPoint *destinationPoint = [AMapGeoPoint locationWithLatitude:self.ordersDetailsModel.originLat longitude:self.ordersDetailsModel.originLng];
        
        [self calculateRouteWithStartPoint:[AMapNaviPoint locationWithLatitude:startPoint.latitude longitude:startPoint.longitude] endPoint:[AMapNaviPoint locationWithLatitude:destinationPoint.latitude longitude:destinationPoint.longitude] wayPoints:nil]; // 重新规划导航路线
    }else if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 接到乘客,前往目的地
        
        if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
            
            AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude];
            
            self.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth;
//            [self.driveManager setDetectedMode:AMapNaviDetectedModeCameraAndSpecialRoad]; // 开启巡航模式
            [[NaviDriveManager shareManager] setDetectedMode:AMapNaviDetectedModeSpecialRoad];
            self.navigationActivityBackView.hidden = YES;
            [self.navigationActivityView stopAnimating];
            
            [self calculateRouteWithStartPoint:[AMapNaviPoint locationWithLatitude:startPoint.latitude longitude:startPoint.longitude] endPoint:[AMapNaviPoint locationWithLatitude:startPoint.latitude longitude:startPoint.longitude] wayPoints:nil]; // 重新规划导航路线
            
        }else {
           
            AMapGeoPoint *startPoint = [AMapGeoPoint locationWithLatitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.latitude longitude:[LocationManager shareManager].userLocationModel.userLocation.coordinate.longitude];
            AMapGeoPoint *destinationPoint = [AMapGeoPoint locationWithLatitude:self.ordersDetailsModel.destLat longitude:self.ordersDetailsModel.destLng];
            
            [self calculateRouteWithStartPoint:[AMapNaviPoint locationWithLatitude:startPoint.latitude longitude:startPoint.longitude] endPoint:[AMapNaviPoint locationWithLatitude:destinationPoint.latitude longitude:destinationPoint.longitude] wayPoints:nil]; // 重新规划导航路线
        }

    }else if (self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
        
        
    }
}

/**
 进行路径规划
 */
- (void)calculateRouteWithStartPoint:(AMapNaviPoint *)startPoint endPoint:(AMapNaviPoint *)endPoint wayPoints:(NSArray<AMapNaviPoint *> *)wayPoints
{
    if (startPoint == nil || endPoint == nil) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:@"导航失败" onView:nil hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        return;
    }
    
//    BOOL isSuccess = [self.driveManager calculateDriveRouteWithStartPoints:@[startPoint]
//                                                                 endPoints:@[endPoint]
//                                                                 wayPoints:wayPoints
//                                                           drivingStrategy:AMapNaviDrivingStrategySingleDefault];
    
    
    BOOL isSuccess = [[NaviDriveManager shareManager] calculateDriveRouteWithStartPoints:@[startPoint]
                                                                 endPoints:@[endPoint]
                                                                 wayPoints:wayPoints
                                                           drivingStrategy:AMapNaviDrivingStrategySingleDefault];
    if (isSuccess) {
        
        [self.navigationActivityView stopAnimating];
        self.navigationActivityBackView.hidden = YES;
        [self.activityIndicatorView stopAnimating];
        self.calculationTimeAndDistanceBackView.hidden = YES;
        
        [self.driveView setMapZoomLevel:15.0];
        [self.driveView setCameraDegree:0.0];
        self.driveView.trackingMode = AMapNaviViewTrackingModeCarNorth;
        self.driveView.showMode = AMapNaviDriveViewShowModeCarPositionLocked;
    }
}


#pragma mark - AMapNaviDriveManagerDelegate: 导航管理器代理
// 路径规划成功
- (void)driveManagerOnCalculateRouteSuccess:(AMapNaviDriveManager *)driveManager
{

    
    if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
        
        if (self.ordersDetailsModel.subStatus == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [[NaviDriveManager shareManager] stopNavi];
                [self.driveView setEndPointImage:[UIImage imageNamed:@"blank"]];
                self.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth;
                [[NaviDriveManager shareManager] removeDataRepresentative:self];
                [[NaviDriveManager shareManager] removeDataRepresentative:self.driveView];
            });
            
        }
    }else {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NaviDriveManager shareManager] addDataRepresentative:self];
            [[NaviDriveManager shareManager] addDataRepresentative:self.driveView];
            self.isOnCalculateRouteSuccess = YES;
        });
        
        [[NaviDriveManager shareManager] startGPSNavi];

    }
}



// 发生错误
- (void)driveManager:(AMapNaviDriveManager *)driveManager error:(NSError *)error {
    

    self.isOnCalculateRouteSuccess = NO;
}

// 路径规划失败
- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteFailure:(NSError *)error {
    

    self.isOnCalculateRouteSuccess = NO;
}

// 开启导航
- (void)driveManager:(AMapNaviDriveManager *)driveManager didStartNavi:(AMapNaviMode)naviMode {
    
    // 这一个页面会进行多次的路线重新规划,每次重新规划都需要刷新剩余距离,和剩余时间
    [self refreshDistanceAndTimeWithMapPath:driveManager.naviRoute];

}

// 路线偏移重新规划路线
- (void)driveManagerNeedRecalculateRouteForYaw:(AMapNaviDriveManager *)driveManager {
    
    self.isOnCalculateRouteSuccess = NO;
    
//    [self.driveManager recalculateDriveRouteWithDrivingStrategy:(AMapNaviDrivingStrategySingleDefault)]; // 重新规划路径
    [[NaviDriveManager shareManager] recalculateDriveRouteWithDrivingStrategy:AMapNaviDrivingStrategySingleDefault];
}


/**
 到达目的地
 */
- (void)driveManagerOnArrivedDestination:(AMapNaviDriveManager *)driveManager {
    
    
}

/// 实时导航语音播报
- (void)driveManager:(AMapNaviDriveManager *)driveManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType {
    
    if (self.isPlayingNaviInfo) {
        
        IflyMSCManager *iflyMSCManager = [IflyMSCManager startSyntheticSpeechForNaviWithText:soundString];
        [iflyMSCManager.iFlySpeechSynthesizer setParameter:[NSString stringWithFormat:@"50"] forKey:[IFlySpeechConstant SPEED]]; // 设置语音播报速度50
    }
}


/// 是否播报导航语音
- (BOOL)driveManagerIsNaviSoundPlaying:(AMapNaviDriveManager *)driveManager {

    
    if ([IflyMSCManager shareManager].state == NotStart) {
        
        return NO;
    }else if ([IflyMSCManager shareManager].state == Playing) {
        
        return YES;
    }else if ([IflyMSCManager shareManager].state == Paused) {
        
        return NO;
    }else {
        
        return NO;
    }
}


/**
 *  导航信息更新回调
 *
 *  @param naviInfo 导航信息,参考 AMapNaviInfo 类
 */
- (void)driveManager:(AMapNaviDriveManager *)driveManager updateNaviInfo:(nullable AMapNaviInfo *)naviInfo {
    
    CGFloat distance = naviInfo.routeRemainDistance / 1000.00; // 剩余公里
    if (distance < 1) {
        
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2f米" , distance * 1000];
    }else {
        
        self.distanceLabel.text = [NSString stringWithFormat:@"%.2f公里" , distance];
    }
    
    CGFloat time = naviInfo.routeRemainTime / 60.0; // 转化分钟
    self.timeLabel.text = [NSString stringWithFormat:@"%.f分钟" , time];
}

- (void)simulationDriveWithAMapNaviLocation:(nullable AMapNaviLocation *)naviLocation {
    
    double lat = naviLocation.coordinate.latitude;
    double lng = naviLocation.coordinate.longitude;
    double angle = (double)naviLocation.heading;
    
    if (lat == 0 || lng == 0) { // 如果没有获取到正确的位置信息不执行
        
        return;
    }
    
    self.newLat = lat;
    self.newLng = lng;
    self.newAngle = angle;
    
    if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
        
        MATraceLocation *traceLocation = [[MATraceLocation alloc] init];
        traceLocation.loc = CLLocationCoordinate2DMake(lat, lng);
        traceLocation.angle = angle;
        [self.tracePointArray addObject:traceLocation];
        
        CLLocationCoordinate2D firstLocation = CLLocationCoordinate2DMake(traceLocation.loc.latitude, traceLocation.loc.longitude);
        NSValue *endValue = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"orderUuidLocation_%@" , self.ordersDetailsModel.uuid]];
        if (endValue != nil) {
            
            CLLocationCoordinate2D endLocation = [endValue MACoordinateValue];
            
            if (endLocation.latitude == 0 || endLocation.longitude == 0) {
                
                self.tempDistanceOfTwoPoint = 0.0;
            }else {
                
                self.tempDistanceOfTwoPoint = [MapGeometryCalculationManager calculateTheDistanceBetweenStartMAMapPoint:firstLocation endMAMapPoint:endLocation] / 1000.0;
            }
        }else {
            
            self.tempDistanceOfTwoPoint = 0.0;
        }
    }

    if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 如果接到乘客,开始添加位置点
        
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
        [self.trajectoryCorrectionManager add:coordinate];
        
        if (self.trajectoryCorrectionManager != nil) {
            
            double distance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;

            self.hasDriverDistance.text = [NSString stringWithFormat:@"实际行驶距离:%.4f公里" , distance];
        }
    }
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager updateNaviLocation:(nullable AMapNaviLocation *)naviLocation {
    

}

#pragma 导航巡航模式
- (void)driveManager:(AMapNaviDriveManager *)driveManager updateCruiseInfo:(AMapNaviCruiseInfo *)cruiseInfo
{
    NSLog(@"updateCruiseInfo:%@", cruiseInfo);
}

- (void)driveManager:(AMapNaviDriveManager *)driveManager updateTrafficFacilities:(NSArray<AMapNaviTrafficFacilityInfo *> *)trafficFacilities
{
    NSLog(@"updateTrafficFacilities:%@", trafficFacilities);
}



#pragma mark - 注册司机位置发生改变的通知
- (void)registerDriverHasChangedLocation {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upLoadDriverLocationInfo:) name:NotificationName_UserLocationChanged object:nil];
}

#pragma mark - 获取司机最新的位置点
- (void)upLoadDriverLocationInfo:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_UserLocationChanged]) {
        
        
        self.tempNumber += 1;
        
        NSDictionary *locationDic = aNotification.object;
        
        double lat = [locationDic[@"lat"] doubleValue];
        double lng = [locationDic[@"lng"] doubleValue];
        double angle = [locationDic[@"angle"] doubleValue];
        
        
        
        if (lat == 0 || lng == 0) { // 如果没有获取到正确的位置信息不执行
            
            return;
        }
        
        self.newLat = lat;
        self.newLng = lng;
        self.newAngle = angle;
        
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
        [self.trajectoryCorrectionManager add:coordinate];
        
        double twoPointDistance = [self.trajectoryCorrectionManager getThelastedDistance] /  1000.0;
        double totalDistance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;
        
        if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers || self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {

            
            [[SendLocationManager shareManager] configureModelInfoOfHasOrderWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:self.orderState isSendImmediately:NO];
        }


        if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 如果接到乘客,开始添加位置点
            
            [[SendLocationManager shareManager] configureModelInfoOfOngoingOrderAndSendLocationInfoWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:self.orderState isSendImmediately:NO];
        }
        
        
    }
}

#pragma mark - 默认配置属性
/**
 初始化默认属性
 */
- (void)configureDefaultAttributes {

    self.isPlayingNaviInfo = NO;
    
    self.pointImageView.layer.cornerRadius = self.pointImageView.frame.size.height / 2.0;
    self.pointImageView.layer.masksToBounds = YES;
    
    [self.activityIndicatorView startAnimating];
    self.calculationTimeAndDistanceBackView.hidden = NO;
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    
//    self.timer = [NSTimer timerWithTimeInterval:15 target:self selector:@selector(uploadDriverInfo:) userInfo:nil repeats:YES];
//    [[NSRunLoop  mainRunLoop] addTimer:self.timer forMode:(NSRunLoopCommonModes)]; // UI 发生变化不会中断定时器
//    [self.timer fire];
    
    self.isReceivedMsgOfOrderCanceled = NO; // 是否收到取消订单的通知,没有
    
    
    self.leftBarButtonItem.image = [QXDriverConfiguration imageWithName:@"nav_icon_back_white"];
    [self.navigationButton setImage:[QXDriverConfiguration imageWithName:@"public_daohang"] forState:UIControlStateNormal];
    [self.callPhoneButton setImage:[QXDriverConfiguration imageWithName:@"public_call2"] forState:UIControlStateNormal];
    self.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
    self.bottomImageView.image = [QXDriverConfiguration imageWithName:@"public_pic_dagou"];
    [self.positioningButton setImage:[QXDriverConfiguration imageWithName:@"public_map_dingwei"] forState:UIControlStateNormal];
    [self.roadConditionsButton setImage:[QXDriverConfiguration imageWithName:@"public_map_lukuang"] forState:UIControlStateNormal];
    
    // 更改导航条字体颜色大小
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[UIColor whiteColor]
       }];
    
    
    // 地图load开启
    self.navigationActivityBackView.layer.cornerRadius = self.navigationActivityView.frame.size.height / 2.0;
    self.navigationActivityBackView.layer.masksToBounds = YES;
    [self.navigationActivityView startAnimating];
    
    /// 隐藏成功图片
    self.bottomImageView.hidden = YES;
    
    /// 订单子状态(100.等待应答 200.等待接驾-预约 201.等待接驾-已出发未到达 202.等待接驾-已到达* 300.行程开始 400.待支付 500.已完成(待评价) 501.已完成-已评价 600.取消-自主取消* 601.取消-后台取消 602.取消-应答前取消)
    [self refreshOrderStateUI];
    
    // 起点
    if (self.ordersDetailsModel.originAddress) {
        
        switch (self.orderState) {
            case OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers:
            case OrderStatusEnumCode_DriverArrived_WaitingForPassengers:
                //            case OrderState_WaitingPassenger:
            {
                self.startLabel.text = self.ordersDetailsModel.originAddress;
                break;
            }
            case OrderStatusEnumCode_PickedUpPasengers_StrokeStart: { // 接到乘客
                
                self.startLabel.text = self.ordersDetailsModel.destAddress;
                break;
            }
            default:
                break;
        }
    }
    // 截取
    NSString *phone = [self.userPassengerModel.mobile substringFromIndex:7];
    self.phoneTailNumberLabel.text = [NSString stringWithFormat:@"尾号%@",phone];
    // 滑动调接口
    [self slidingWithAPI];
    
    
    self.timeAccumulation = 0;

}



#pragma mark - 上传司机位置信息到服务器
- (void)uploadDriverInfo:(NSTimer *)timer {
    
    return;  // 这里需要废弃
    
    if (self.timeAccumulation == 3 || self.timeAccumulation == 0) { // 每过30s拉取一次超时等待费用
        
        if (self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) { // 如果订单处于等待乘客状态,刷新超时等待费用
            
            [self getWaitingFare];
        }
        
        // 实时跟新价格
        if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
            
            if (self.timeAccumulation == 0) { // 刚进来的时候获取一下最新的价格,针对app挂掉
                
                [self getDriverRealTimePrice];
            }
            
        }
        
        self.timeAccumulation = 1;
    }
    
    self.timeAccumulation += 1;
    
    [self prepareLocationInfoForSendingToService];

}



#pragma mark - 准备位置信息发送到服务端
- (void)prepareLocationInfoForSendingToService {
    
    // 与上一点的距离
    double distance = self.newDistance;
    // 纬度
    double lat = self.newLat;
    // 精度
    double lng = self.newLng;
    
    // 角度
    NSString *angle = [NSString stringWithFormat:@"%ld" , (long)self.newAngle];
    
    if (lat == 0 || lng == 0) { // 如果位置信息错误不向服务端发送消息
        
        return;
    }
    
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@(distance) forKey:@"distance"];
    [parameters setValue:@(lat) forKey:@"lat"];
    [parameters setValue:@(lng) forKey:@"lng"];
    [parameters setValue:angle forKey:@"angle"];
    [parameters setValue:@"UPLOAD_LOCATION" forKey:@"type"];
    [parameters setValue:@([[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]) forKey:@"driverType"];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    NSDate *date = [NSDate date];
    NSString *date2 = [NSString stringWithFormat:@"%.f", [date timeIntervalSince1970] * 1000];
    [parameters setValue:date2 forKey:@"locationUuid"];
    [parameters setValue:date2 forKey:@"uploadTime"];
    [parameters setValue:[QXDataManager getValueForKey:QXAppId] forKey:@"appid"];
    QXYYUserDriverModel*driver = [QXYYUserDriverModel QXYY_unarchiveObject];
    [parameters setValue:driver.uuid forKey:@"driverUuid"];
    [parameters setValue:driver.uuid forKey:@"clientUuid"];
    [parameters setValue:driver.token forKey:@"token"];
    [parameters setValue:@(self.orderState) forKey:@"orderStatus"];
    
    if ((self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) || (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) || (self.orderState == OrderStatusEnumCode_NoOrder)) {
        
        [parameters setValue:@(0) forKey:@"mileage"]; // 单位公里
        [[QXSocketManager manager] send:parameters];
    }else if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) { // 开始送乘客,发送实际行驶距离
        

        double distance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;
        [parameters setValue:@(distance) forKey:@"mileage"];

        if ([self.ordersDetailsModel.typeTrip integerValue] == 2 || [self.ordersDetailsModel.typeTrip integerValue] == 4 || [self.ordersDetailsModel.typeTrip integerValue] == 5 || [self.ordersDetailsModel.typeTrip integerValue] == 6 || [self.ordersDetailsModel.typeTrip integerValue] == 7) {
            
            [[QXSocketManager manager] send:parameters];
        }
    }
}


#pragma mark - 行程中获取上传司机位置拿到的报文
- (void)regisetrUPLOAD_LOCATION_RESPONSENotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getTheReportOfLongLink:) name:NotificationName_UPLOAD_LOCATION_RESPONSE object:nil];
}

- (void)getTheReportOfLongLink:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_UPLOAD_LOCATION_RESPONSE]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.fareButton setAttributedTitle:[self retureFareButtonAttributesStringWithString:[NSString stringWithFormat:@"%.1f元" , [aNotification.object[@"totalFare"] doubleValue]]] forState:UIControlStateNormal];
        });
    }
}




/**
 刷新底部,title的标题的UI
 */
- (void)refreshOrderStateUI {
    
    if (self.ordersDetailsModel.subStatus==200) {
        
        QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
            
            self.title = @"去接货";
            self.statusLabel.text = @"去接货";
            self.bottomView.titleLabel.text = @"到达发货地点";
        }else{
            
            self.title = @"去接乘客";
            self.statusLabel.text = @"去接乘客";
            self.bottomView.titleLabel.text = @"到达上车地点";
        }
        
        self.startLabel.hidden = NO;
        self.pointImageView.hidden = NO;
        
        self.orderState = OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers;

        self.slidingButtonMargin_ToLeft.constant = 0.0;

        self.navigationButton.hidden = NO;
        self.getOnLabel.hidden = YES;
    }else if (self.ordersDetailsModel.subStatus==210) {
        
        QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
            
            self.title = @"去接货";
            self.statusLabel.text = @"去接货";
            self.bottomView.titleLabel.text = @"到达发货地点";
        }else {
            
            self.title = @"去接乘客";
            self.statusLabel.text = @"去接乘客";
            self.bottomView.titleLabel.text = @"到达上车地点";
        }
        
        self.startLabel.hidden = NO;
        self.pointImageView.hidden = NO;
        
        self.orderState = OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers;

        self.slidingButtonMargin_ToLeft.constant = 0.0;
        self.navigationButton.hidden = NO;
        self.displayViewHeight.constant = 35.0;
        self.getOnLabel.hidden = YES;
    }else if (self.ordersDetailsModel.subStatus==220) {
        self.title = @"等待中";
        QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
            
            self.statusLabel.text = @"等待接货";
            self.bottomView.titleLabel.text = @"货物已装车";
        }else {
            self.statusLabel.text = @"等待乘客";
            self.bottomView.titleLabel.text = @"乘客已上车";
        }
        
        self.orderState = OrderStatusEnumCode_DriverArrived_WaitingForPassengers;

        if ([self.ordersDetailsModel.typeTrip integerValue] == 2 || [self.ordersDetailsModel.typeTrip integerValue] == 4 || [self.ordersDetailsModel.typeTrip integerValue] == 5 || [self.ordersDetailsModel.typeTrip integerValue] == 6 || [self.ordersDetailsModel.typeTrip integerValue] == 7) {
            
            self.slidingButtonMargin_ToLeft.constant = 100.0;
        }else if ([self.ordersDetailsModel.typeTrip integerValue] == 1) {
            
            self.slidingButtonMargin_ToLeft.constant = 0.0;
        }
        
        self.startLabel.hidden = NO;
        self.pointImageView.hidden = NO;
        
        self.navigationButton.hidden = YES;
        self.navigationActivityView.hidden = YES;
        self.calculationTimeAndDistanceBackView.hidden = YES;
        self.displayViewHeight.constant = 0.0;
        self.getOnLabel.hidden = NO;
    }else if (self.ordersDetailsModel.subStatus==300) {
        self.title = @"行程中";
        
        QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
        if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
            
            self.statusLabel.text = @"去送货";
        }else {
            self.statusLabel.text = @"去送乘客";
        }
        
        if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
            
            self.startLabel.hidden = YES;
            self.pointImageView.hidden = YES;
            self.navigationButton.hidden = YES;
            self.navigationActivityBackView.hidden = YES;
            self.displayViewHeight.constant = 0.0;
            self.displayView.hidden = YES;
        }else {
            
            self.startLabel.hidden = NO;
            self.pointImageView.hidden = NO;
            self.navigationButton.hidden = NO;
            self.displayViewHeight.constant = 35.0;
            self.displayView.hidden = NO;
        }
        
        self.bottomView.titleLabel.text = @"到达目的地";
        self.orderState = OrderStatusEnumCode_PickedUpPasengers_StrokeStart;

        if ([self.ordersDetailsModel.typeTrip integerValue] == 2 || [self.ordersDetailsModel.typeTrip integerValue] == 4 || [self.ordersDetailsModel.typeTrip integerValue] == 5 || [self.ordersDetailsModel.typeTrip integerValue] == 6 || [self.ordersDetailsModel.typeTrip integerValue] == 7) { // 2: 专车; 4: 快车; 5: 货的; 6: 骑手; 7:搬家
            
            self.slidingButtonMargin_ToLeft.constant = 100.0;
        }else if ([self.ordersDetailsModel.typeTrip integerValue] == 1) {
            
            self.slidingButtonMargin_ToLeft.constant = 0.0;
        }
        
        self.getOnLabel.hidden = YES;
    }
}



#pragma mark - gotoPickUpPassenger

/**
 去接乘客网络请求
 */
- (void)gotoPickUpPassenger {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    [DLLApiManager gotoPickUpPassengerWithParameters:parameters success:^(id data) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            
            
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}




#pragma mark -滑动调接口
- (void)slidingWithAPI {
    
    __weak typeof(self) weakSelf = self;
    [self.bottomView setDoneHandler:^{
        __strong typeof(self) strongSelf = weakSelf;
        strongSelf.bottomView.titleLabel.hidden = YES;
        strongSelf.bottomView.iconImage = nil;
        strongSelf.bottomView.userInteractionEnabled = NO; // 进制交互
        if ([strongSelf.bottomView.titleLabel.text isEqualToString:@"到达上车地点"] || [strongSelf.bottomView.titleLabel.text isEqualToString:@"到达发货地点"]) {
            // 司机到达上车地点
            [strongSelf arrivingAtTheBoardingPoint];
        }else if ([strongSelf.bottomView.titleLabel.text isEqualToString:@"乘客已上车"] || [strongSelf.bottomView.titleLabel.text isEqualToString:@"货物已装车"]) {
            
            // 司机接到乘客
            [strongSelf passengersAreOnCar];
        }else if ([strongSelf.bottomView.titleLabel.text isEqualToString:@"到达目的地"]) {
            // 司机到达目的
            [strongSelf driverArrivesAtTheDestination];
        }
    }];
}

#pragma mark -司机到达上车地点接口
- (void)arrivingAtTheBoardingPoint {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    
    
    
    double twoPointDistance = [self.trajectoryCorrectionManager getThelastedDistance] /  1000.0;
    double totalDistance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;
    [[SendLocationManager shareManager] configureModelInfoOfHasOrderWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:(OrderStatusEnumCode_DriverArrived_WaitingForPassengers) isSendImmediately:YES];
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager arrivingAtTheBoardingPointWithParameters:dic success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (NetWork_Success) {
            
            strongSelf.bottomImageView.hidden = NO;
            
            strongSelf.orderState = OrderStatusEnumCode_DriverArrived_WaitingForPassengers;
            
            
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
            
            
            if ([MapManager shareManager].currentMapType == MapTypeGD) {
                
                // 显示等待乘客的地图
                strongSelf.mapView.alpha = 1.0;
                [strongSelf.mapView setUserTrackingMode:(MAUserTrackingModeFollow)];
            }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
                
                // 显示等待乘客的地图
                strongSelf.mapView.alpha = 1.0;
                [strongSelf.mapView setUserTrackingMode:(MAUserTrackingModeFollow)];
                
                if (strongSelf.orginPin != nil) {
                    
                    [strongSelf.mapboxMapView removeAnnotation:self.orginPin];
                }
                
                if (strongSelf.destPin != nil) {
                    
                    [strongSelf.mapboxMapView removeAnnotation:self.destPin];
                }
                
                if (strongSelf.currentRouteLine != nil) {
                    
                    [strongSelf.mapboxMapView removeOverlay:strongSelf.currentRouteLine];
                }
            }
            
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{

                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
                if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                    
                    strongSelf.bottomView.titleLabel.text = @"货物已装车";
                    strongSelf.statusLabel.text = @"等待接货";
                }else {
                    
                    strongSelf.bottomView.titleLabel.text = @"乘客已上车";
                    strongSelf.statusLabel.text = @"等待乘客";
                }
                
                
                strongSelf.title = @"等待中";
                strongSelf.slidingButtonMargin_ToLeft.constant = 100.0;
                strongSelf.ordersDetailsModel.subStatus = OrderStatusEnumCode_DriverArrived_WaitingForPassengers;
                [strongSelf refreshOrderStateUI];
                
            });
        }else {
            /// 主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showWithText:NetWork_Message onView:self.view hiddenDuration:1];
                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
                if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                    
                    strongSelf.bottomView.titleLabel.text = @"到达发货地点";
                }else {
                    
                    strongSelf.bottomView.titleLabel.text = @"到达上车地点";
                }
                
                [strongSelf refreshOrderStateUI];
            });
        }
        
        weakSelf.bottomView.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        /// 主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.bottomView.userInteractionEnabled = NO;
            [MBProgressHUD showWithText:@"请检查网络..." onView:weakSelf.view hiddenDuration:1];
            strongSelf.bottomImageView.hidden = YES;
            strongSelf.bottomView.titleLabel.hidden = NO;
            strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
            
            QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                
                strongSelf.bottomView.titleLabel.text = @"到达发货地点";
            }else {
                
                strongSelf.bottomView.titleLabel.text = @"到达上车地点";
            }
            strongSelf.bottomView.userInteractionEnabled = YES;
            [strongSelf refreshOrderStateUI];
        });
    }];
}
#pragma mark -司机接到乘客接口
- (void)passengersAreOnCar {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    double totalDistance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0;
    // 公里,告诉服务端空驶行驶里程
    [dic setValue:@(totalDistance) forKey:@"waitMile"];
    
    double twoPointDistance = [self.trajectoryCorrectionManager getThelastedDistance] /  1000.0;

    [[SendLocationManager shareManager] configureModelInfoOfHasOrderWithTwoPointDistance:twoPointDistance totalDistace:totalDistance orderUuid:self.ordersDetailsModel.uuid orderStatus:(OrderStatusEnumCode_PickedUpPasengers_StrokeStart) isSendImmediately:YES];
    
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager passengersAreOnCarWithParameters:dic success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        if (NetWork_Success) {
            
            strongSelf.bottomImageView.hidden = NO;
            
            // 清除之前的空驶里程,开始计算载客里程
            [strongSelf.trajectoryCorrectionManager cleanCache];
            
            strongSelf.orderState = OrderStatusEnumCode_PickedUpPasengers_StrokeStart;


            [QXDataManager saveValue:@"1" forKey:[NSString stringWithFormat:@"%@_TotalDistance" , self.ordersDetailsModel.uuid]];
            
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                strongSelf.bottomView.titleLabel.text = @"到达目的地";
                QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
                if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                    
                    strongSelf.statusLabel.text = @"去送货";
                }else {
                    
                    strongSelf.statusLabel.text = @"去送乘客";
                }
                
                
                
                strongSelf.title = @"行程中";
                strongSelf.startLabel.text = self.ordersDetailsModel.destAddress;
                
                strongSelf.mapView.alpha = 0.0;
                
                [strongSelf getDriverRealTimePrice];
                
                strongSelf.orderState = OrderStatusEnumCode_PickedUpPasengers_StrokeStart; // 接到乘客前往目的地
                
                if ([strongSelf.ordersDetailsModel.typeTime isEqualToString:@"3"] || [strongSelf.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
                    
                    
                    strongSelf.calculationTimeAndDistanceBackView.hidden = YES;
                    [strongSelf.activityIndicatorView stopAnimating];


                    strongSelf.ordersDetailsModel.subStatus = OrderStatusEnumCode_PickedUpPasengers_StrokeStart;
                    [strongSelf refreshOrderStateUI];

                    
                    if ([MapManager shareManager].currentMapType == MapTypeGD) {
                        
                        [[NaviDriveManager shareManager] removeDataRepresentative:self];
                        [[NaviDriveManager shareManager] removeDataRepresentative:self.driveView];

                        
                        [strongSelf.driveView setEndPointImage:[UIImage imageNamed:@"blank"]];
                        [strongSelf reDrawMapRoute]; // 重新绘制该地图的路径 , 导航路线
                        strongSelf.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth;
                        //                    [strongSelf.driveManager setDetectedMode:AMapNaviDetectedModeCameraAndSpecialRoad]; // 开启巡航模式
                        [[NaviDriveManager shareManager] setDetectedMode:AMapNaviDetectedModeCameraAndSpecialRoad];
                    }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
                        
                        
                    }
                    

                }else {
                    
                    strongSelf.calculationTimeAndDistanceBackView.hidden = NO;
                    [strongSelf.activityIndicatorView startAnimating];
                    strongSelf.ordersDetailsModel.subStatus = OrderStatusEnumCode_PickedUpPasengers_StrokeStart;
                    if ([MapManager shareManager].currentMapType == MapTypeGD) {
                        
                        [strongSelf reDrawMapRoute]; // 重新绘制该地图的路径 , 导航路线
                    }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
                        
                        [strongSelf reDrawMapBoxRoute];
                    }
                    
                    
                    [strongSelf refreshOrderStateUI];
                    
                }
            });
        }else {
            /// 主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:1];
                
                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
                if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                    strongSelf.bottomView.titleLabel.text = @"货物已装车";
                }else {
                    strongSelf.bottomView.titleLabel.text = @"乘客已上车";
                }
                [strongSelf refreshOrderStateUI];
            });
        }
        
        strongSelf.bottomView.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        
        __strong typeof(self) strongSelf = weakSelf;
        /// 主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            strongSelf.bottomView.userInteractionEnabled = YES;
            [MBProgressHUD showWithText:@"请检查网络..." onView:strongSelf.view hiddenDuration:1];
            
            strongSelf.bottomImageView.hidden = YES;
            strongSelf.bottomView.titleLabel.hidden = NO;
            strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
            QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
            if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
                
                strongSelf.bottomView.titleLabel.text = @"货物已装车";
            }else {
                
                strongSelf.bottomView.titleLabel.text = @"乘客已上车";
            }
            
            strongSelf.bottomView.userInteractionEnabled = YES;
            [strongSelf refreshOrderStateUI];
        });
    }];
}
#pragma mark -司机到达目的地接口
- (void)driverArrivesAtTheDestination {
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    double distance = [self.trajectoryCorrectionManager getTheLastTotalDistance] / 1000.0; // 获取位置信息,并转化公里
    double twoPointDistance = [self.trajectoryCorrectionManager getThelastedDistance] / 1000.0; // 获取最近两点之间的距离
    [dic setValue:@(distance) forKey:@"tripDistance"]; // 实际的行驶距离
    
    if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
        
        LocationManager *locationManager = [LocationManager shareManager];
        
        if (locationManager.userLocationModel) {
            
            NSString *destAddress = locationManager.userLocationModel.POIName; // 终点地址区域
            NSString *destDetailAddress = locationManager.userLocationModel.district; // 终点的详细地址
            NSString *destCity = locationManager.userLocationModel.city; // 终点城市
            double destLng = locationManager.userLocationModel.userLocation.coordinate.longitude; // 终点经度
            double destLat = locationManager.userLocationModel.userLocation.coordinate.latitude ; // 终点纬度
            
            [dic setValue:destAddress forKey:@"destAddress"];
            [dic setValue:destDetailAddress forKey:@"destDetailAddress"];
            [dic setValue:destCity forKey:@"destCity"];
            [dic setValue:@(destLng) forKey:@"destLng"];
            [dic setValue:@(destLat) forKey:@"destLat"];
            if (destLat == 0 || destLng == 0) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    MBProgressHUD *mb = [MBProgressHUD showWithText:@"请求失败，请重试" onView:self.view hiddenDuration:2.0];
                    mb.userInteractionEnabled = YES;
                    self.bottomView.titleLabel.hidden = NO;
                    self.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                    self.bottomView.titleLabel.text = @"到达目的地";
                    self.bottomView.userInteractionEnabled = YES;
                });
                return;
            }
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:@"请求失败，请重试" onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = YES;
                self.bottomView.titleLabel.hidden = NO;
                self.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                self.bottomView.titleLabel.text = @"到达目的地";
                self.bottomView.userInteractionEnabled = YES;
            });
            return;
        }
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    

    
    [[SendLocationManager shareManager] configureModelInfoOfOngoingOrderAndSendLocationInfoWithTwoPointDistance:twoPointDistance totalDistace:distance orderUuid:self.ordersDetailsModel.uuid orderStatus:(OrderStatusEnumCode_PassengersArrivedDestination) isSendImmediately:YES];
    
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager driverArrivesAtTheDestinationWithParameters:dic success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            strongSelf.bottomImageView.hidden = NO;
            
            [strongSelf cancelNotification];
            
            // 设置无订单空驶状态
            [[SendLocationManager shareManager] configureModelInfoOfNoOrder];
            
            
            /// 这里是关闭正在合成,正在播报的导航语音
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_Ifly_PausePlay object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_Ifly_CancelSynthesis object:nil];

            // 送达乘客后开启上传司机位置的定时器,并销毁导航控制器,导航按钮不可用
            if ([strongSelf.ordersDetailsModel.typeTime isEqualToString:@"3"] || [strongSelf.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
                
//                [strongSelf.driveManager setDetectedMode:AMapNaviDetectedModeNone]; // 关闭巡航模式
                [[NaviDriveManager shareManager] setDetectedMode:AMapNaviDetectedModeNone];
            }else {
                
//                [strongSelf.driveManager removeDataRepresentative:self]; // 关闭导航模式
                [[NaviDriveManager shareManager] removeDataRepresentative:self];
                [[NaviDriveManager shareManager] removeDataRepresentative:self.driveView];
            }
            
            [[OrderClosingManager shareManager] closeNotification];
            
            strongSelf.navigationButton.userInteractionEnabled = NO;

            if (strongSelf.timer) {
                [strongSelf.timer invalidate];
                strongSelf.timer = nil;
            }
            
            /// 最后一次上传位置信息
            [strongSelf uploadDriverInfo:nil];
            
            strongSelf.ordersDetailsModel.subStatus = OrderStatusEnumCode_PassengersArrivedDestination; // 订单状态,结束行程
            
            /// 清楚缓存
            [strongSelf.trajectoryCorrectionManager cleanCache];
            
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                
                if ([strongSelf.ordersDetailsModel.typeTrip integerValue]==1) { // 出租车
                    
                    endTheTripViewController *vc = [endTheTripViewController shareSelf];
                    vc.title = @"结算";
                    vc.ordersDetailsModel = strongSelf.ordersDetailsModel;
                    vc.userPassengerModel = strongSelf.userPassengerModel;
                    [strongSelf.navigationController pushViewController:vc animated:YES];
                    
                }else  {
                    carEndTheTripViewController *vc = [carEndTheTripViewController shareSelf];
                    vc.ordersDetailsModel = self.ordersDetailsModel;
                    vc.userPassengerModel = self.userPassengerModel;
                    vc.title = @"结算";
                    [strongSelf.navigationController pushViewController:vc animated:YES];
                }
                
                [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];

            });
        }else {
            /// 主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:1];
                
                strongSelf.bottomImageView.hidden = YES;
                strongSelf.bottomView.titleLabel.hidden = NO;
                strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
                strongSelf.bottomView.titleLabel.text = @"到达目的地";
                [strongSelf refreshOrderStateUI];
                [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            });
        }
        
        strongSelf.bottomView.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        /// 主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.bottomView.userInteractionEnabled = YES;
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            [MBProgressHUD showWithText:@"请检查网络..." onView:strongSelf.view hiddenDuration:1];
            
            strongSelf.bottomImageView.hidden = YES;
            strongSelf.bottomView.titleLabel.hidden = NO;
            strongSelf.bottomView.iconImage = [QXDriverConfiguration imageWithName:@"public_pic_go"];
            strongSelf.bottomView.titleLabel.text = @"到达目的地";
            strongSelf.bottomView.userInteractionEnabled = YES;
            [strongSelf refreshOrderStateUI];
        });
    }];
}

#pragma mark - 获取实时价格的接口
/**
 获取司机实时价格接口
 */
- (void)getDriverRealTimePrice {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverGetRealTimePriceWithParameters:parameters success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (NetWork_Success) {
                
                [strongSelf.fareButton setAttributedTitle:[strongSelf retureFareButtonAttributesStringWithString:[NSString stringWithFormat:@"%.1f元" , [data[@"data"][@"totalFare"] doubleValue]]] forState:UIControlStateNormal];
            }else {
            
                [strongSelf.fareButton setTitle:@"--元" forState:(UIControlStateNormal)]; // 如果获取失败,那么显示--站位符号
            }
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.fareButton setTitle:@"--元" forState:(UIControlStateNormal)]; // 如果获取失败,那么显示--站位符号
        });
    }];
}

- (NSMutableAttributedString *)retureFareButtonAttributesStringWithString:(NSString *)string {
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    
    [attrStr addAttribute:NSForegroundColorAttributeName value:Color_4F5A67 range:NSMakeRange(0, string.length - 1)];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:24] range:NSMakeRange(0, string.length - 1)];
    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(string.length - 1, 1)];
    return attrStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - 导航条左侧按钮
- (IBAction)leftBarButtonAction:(id)sender {
    
    [self cancelNotification];
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
//    self.driveManager.delegate = nil;
//    [self.driveManager removeDataRepresentative:self];
//    [self.driveManager removeDataRepresentative:self.driveView];
//    self.driveManager = nil;
    [[NaviDriveManager shareManager] removeDataRepresentative:self.driveView];
    self.driveView.delegate = nil;
    [self.driveView removeFromSuperview];
    self.driveView = nil;
    

    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 查看订单详情
- (IBAction)rightBarButtonAction:(id)sender {
    if (self.orderState == OrderStatusEnumCode_NoOrder || self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) {
        
        orderDetailsViewController *vc = [orderDetailsViewController shareSelf];
        vc.ordersDetailsModel = self.ordersDetailsModel;
        vc.userPassengerModel = self.userPassengerModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (self.orderState == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) { // 这里有取消订单的功能
        
        progressOrderDetailsViewController *vc = [progressOrderDetailsViewController shareSelf];
        vc.ordersDetailsModel = self.ordersDetailsModel;
        vc.userPassengerModel = self.userPassengerModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (self.orderState == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
        
        orderDetailsViewController *vc = [orderDetailsViewController shareSelf];
        vc.ordersDetailsModel = self.ordersDetailsModel;
        vc.userPassengerModel = self.userPassengerModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark -开启导航
- (IBAction)navigationAction:(id)sender {
    
    if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        if (self.isOnCalculateRouteSuccess) { // 如果导航路径规划成功
            
            NaviVC *naviVC = [[NaviVC alloc] init];
            naviVC.driveManager = [NaviDriveManager shareManager];
            if (self.orderState == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) {
                
                naviVC.orderStatusEnumCode = OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers;
            }else {
                
                naviVC.orderStatusEnumCode = OrderStatusEnumCode_PickedUpPasengers_StrokeStart;
            }
            
            __weak typeof(self) weakSelf = self;
            naviVC.closeAction = ^() {
                __strong typeof(self) strongSelf = weakSelf;
                // 内置导航页面销毁后,不允许播报语音
                strongSelf.isPlayingNaviInfo = NO;
                
            };
            
            // 开启内置导航页面后,允许播报语音
            self.isPlayingNaviInfo = YES;
            [self.navigationController pushViewController:naviVC animated:YES];
        }else {
            
            [self reDrawMapRoute]; // 重新规划路径
        }
    }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        if (self.currentRoute != nil) {
            
            MBNavigationViewController *naviVC = [[MBNavigationViewController alloc] initWithRoute:self.currentRoute directions:[MBDirections sharedDirections]];
            [self presentViewController:naviVC animated:YES completion:^{
                
            }];
        }
    }

}
#pragma mark -拨打电话
- (IBAction)callPhoneAction:(UIButton *)sender {
    
    NSString *phone = self.userPassengerModel.mobile;
    
    if (phone != nil && phone.length > 0) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            
            sender.userInteractionEnabled = YES;
        }];
        sender.userInteractionEnabled = NO;
    }
}
#pragma mark -定位
- (IBAction)positioningButton:(id)sender {
    
    if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
            
            self.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth; // 地图指北
            self.driveView.showMode = AMapNaviDriveViewShowModeCarPositionLocked;
            [self.mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
            
        }else {
            
            self.driveView.trackingMode = AMapNaviViewTrackingModeCarNorth; // 车头指北
            self.driveView.showMode = AMapNaviDriveViewShowModeCarPositionLocked;
            [self.mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
        }
    }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        if ([self.ordersDetailsModel.typeTime isEqualToString:@"3"] || [self.ordersDetailsModel.typeTime isEqualToString:@"4"]) {
            
            
            self.driveView.trackingMode = AMapNaviViewTrackingModeMapNorth; // 地图指北
            [self.mapboxMapView resetNorth];
            [self.mapboxMapView setUserTrackingMode:(MGLUserTrackingModeFollowWithHeading)];
        }else {
            
            [self.mapboxMapView resetNorth];
            self.mapboxMapView.userTrackingMode = MGLUserTrackingModeFollowWithHeading;
        }
    }
}

#pragma mark -路况
- (IBAction)roadConditionsAction:(id)sender {
    
    if ([MapManager shareManager].currentMapType == MapTypeGD) {
        
        self.driveView.showTrafficLayer = !self.driveView.showTrafficLayer;
    }else if ([MapManager shareManager].currentMapType == MapTypeMapBox) {
        
        self.mapboxMapView.showsTraffic = !self.mapboxMapView.showsTraffic;
    }
}

#pragma mark -查看价格详情
- (IBAction)fareAction:(id)sender {
    
    DetailsOfChargesVC *detailsOfChargesVC = [DetailsOfChargesVC initDetailsOfChargesVC];
    detailsOfChargesVC.orderUuid = self.ordersDetailsModel.uuid;
    detailsOfChargesVC.orderSubStatus = self.ordersDetailsModel.subStatus;
    [self.navigationController pushViewController:detailsOfChargesVC animated:YES];
}

#pragma mark - 获取超时等待费用
/**
 获取超时等待费用
 */
- (void)getWaitingFare {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager driverOrderWaitingFareDetailsWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [strongSelf.fareButton setAttributedTitle:[self retureFareButtonAttributesStringWithString:[NSString stringWithFormat:@"%.1f元" , [data[@"data"][@"waitFare"] doubleValue]]] forState:UIControlStateNormal];
            });
        }
        
    } failure:^(NSError *error) {
        
        
    }];
}


#pragma mark - 销毁
- (void)dealloc {

    NSLog(@"进行中销毁了");
    
    if (self.driveView != nil) {
        
        NSLog(@"地图No");
        
    }
    
    if (self.driveManager != nil) {
        
        NSLog(@"导航No");
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
